/**
 * 请假记录
 * TODO: 如果需要新增表格 Column ，请注意历史遗留代码中有直接根据下标做修改的逻辑
 */
import React, { Fragment } from 'react';
import { connect } from 'umi';
import moment from 'moment';
import { Form, Input, Table, Card, Row, Col, Button, Divider } from 'antd';
import { formatMessage } from 'umi';
import { QuickForm, utils } from 'vv-frontend-components';
import { Pagination } from '@/components';
import LinkTo from '@/components/LinkTo';
import { CompanyDepartPlus } from '@/containers';
import DateRange from '@/components/DateRange';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Locale from '@/utils/locale';
import { dateConversion, download } from '@/utils/utils';
import { eventTrack } from '@/utils/track';
import AuthComponent from '@/utils/auth/AuthComponent';
import AuthCode from '@/utils/auth/AuthCode';
import { withRoutePage } from '@/utils/enhanceUtils';
import { history } from 'umi'
import { filterUsefulRequestParams } from '@/utils/request';
import styles from './LeaveRecord.less';

const ORDER_MAP = { asc: 'ascend', desc: 'descend' };
class LeaveRecord extends React.Component {
    constructor(props) {
        super(props);
        const { route } = this.props;
        this.authCode = new AuthCode(route.code).authCode;
    }

    componentDidMount() {
        this.queryToForm();
        this.getTypeListAll();
        this.fetchList();
    }

    // query写入form+model
    queryToForm = () => {
        const { location, form } = this.props;
        const { query } = location;
        const { companyCode, departmentCode, employeeName, startTime, endTime, quarter, dateType } = query;
        form.setFieldsValue({
            userName: employeeName,
            companyDepart: { companyId: companyCode, departmentId: departmentCode },
            date: {
                range: [
                    !startTime ? moment().startOf('month') : moment(startTime),
                    !endTime ? moment(new Date()) : moment(endTime)
                ],
                quarter: quarter ? Number(quarter) : 1,
                type: dateType || 'month'
            }
        });
    };

    formatQueryParam = param => {
        if (!param) return [];
        return Array.isArray(param) ? param : [param];
    };

    paramData = _query => {
        const {
            form,
            location: { query }
        } = this.props;
        const { getFieldsValue } = form;
        const { companyDepart = {}, date = { range: [] }, userName } = getFieldsValue();
        const { leaveCode, leaveStatus, orderByField } = query;
        return {
            companyCode: companyDepart?.companyId || '',
            departmentCode: companyDepart?.departmentId || '',
            startTime: date.range[0] ? date.range[0].format('YYYY-MM-DD') : '',
            endTime: date.range[1] ? date.range[1].format('YYYY-MM-DD') : '',
            dateType: date.type,
            employeeName: userName || '',
            pageNo: query.pageNo,
            pageSize: query.pageSize,
            leaveCode: this.formatQueryParam(leaveCode),
            orderByField,
            leaveStatus: this.formatQueryParam(leaveStatus),
            ..._query
        };
    };

    // 获取列表
    fetchList = () => {
        const { dispatch } = this.props;
        setTimeout(() => {
            dispatch({
                type: 'leaveRecord/fetchList',
                payload: filterUsefulRequestParams(this.paramData())
            });
        });
    };

    handleSubmit = async e => {
        e.preventDefault();
        // 埋点
        eventTrack({
            eventName: 'personnel_management_attendance_leaveRecord_search_click',
            eventProps: {
                label: '请假记录-搜索',
                key_works: JSON.stringify(this.paramData({ pageNo: 1 }))
            }
        });
        history.push({ query: this.paramData({ pageNo: 1 }) });
        this.fetchList();
    };

    handleExport = () => {
        const { dispatch } = this.props;
        const { deepTrim } = utils;
        const { pageNo, pageSize, employeeCode, ...restParam } = this.paramData();
        download({
            getData: () =>
                dispatch({
                    type: 'leaveRecord/fetchExport',
                    payload: deepTrim(restParam)
                })
        });
    };

    // 表格表头点击切换排序
    changeTable = async (pagination, filters, sorters) => {
        const {
            location: { query }
        } = this.props;

        const extraQuery = {};
        if (sorters && sorters.field && sorters.order) {
            let sorterField;
            if (sorters.field === 'startTime') {
                sorterField = 'start_time';
            }
            if (sorters.field === 'endTime') {
                sorterField = 'end_time';
            }
            if (sorters.field === 'leaveLong') {
                sorterField = 'leave_long';
            }
            const order = sorters.order.trim().split('end')[0];
            extraQuery.orderByField = `${sorterField} ${order}`;
        } else {
            extraQuery.orderByField = '';
        }

        if (filters) {
            extraQuery.leaveCode = filters?.leaveName;
            extraQuery.leaveStatus = filters?.leaveStatus;
        }

        history.push({ query: { ...query, ...extraQuery, pageNo: 1 } });
        this.fetchList();
    };

    changePagination = async _pagination => {
        // 因为 this.paramData() 操作需要取到 pageSize最新值, 所以这里使用 setTimeout
        setTimeout(() => {
            history.push({ query: this.paramData({ pageNo: _pagination.current, pageSize: _pagination.pageSize }) });
            this.fetchList();
        });
    };

    getTypeListAll = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'leaveRecord/fetchLeaveTypeList'
        });
        dispatch({
            type: 'leaveRecord/fetchDictionaryList',
            payload: {
                code: 'leaveStatus'
            }
        });
    };

    // dot圆点渲染
    renderDot = num => {
        let color = '';
        if (num === '1' || num === '4') {
            color = '#52C41A';
        } else if (num === '2') {
            color = '#FFA22D';
        } else if (num === '3') {
            color = '#FF4D4F';
        }
        return <i className={styles.dot} style={{ background: color }}></i>;
    };

    transformSortOrder = (currentField = '', orderByField = '') => {
        // 兼容服务端数据与 antd 的 sortOrder 参数
        const [field, order] = orderByField.split(' ');
        if (currentField !== field || !ORDER_MAP[order]) {
            return false;
        }
        return ORDER_MAP[order];
    };

    getColumns = () => {
        const {
            leaveRecord: { leaveTypeList, leaveStatus: leaveStatusList },
            location
        } = this.props;
        const { query } = location;
        const { leaveCode = [], orderByField = '', leaveStatus = [] } = query;
        const column = [
            {
                title: `${formatMessage({
                    id: 'stat.absenceList.userNo'
                })}`,
                dataIndex: 'userNo',
                key: 'userNo'
            },
            {
                title: `${formatMessage({
                    id: 'stat.absenceList.userName'
                })}`,
                dataIndex: 'userName',
                key: 'userName',
                width: 90,
                render: (text, record) => {
                    const { applicationNo } = record;
                    // const isOldLeave = /LEAVE/.test(applicationNo);
                    const isOldLeave = applicationNo.indexOf('-') === -1;

                    const newUrl = '/personal/portal/myAuditRead/myAuditReadDetail';
                    const newQuery = { applicationNo };

                    const leaveUrl = isOldLeave
                        ? '/office/institutions/flowManage/fullApprovalProcess/processDetail'
                        : newUrl;

                    const leaveQuery = isOldLeave ? { applicationNo, linkFrom: '1' } : newQuery;

                    return (
                        <span>
                            {record.applicationNo ? (
                                <LinkTo to={leaveUrl} query={leaveQuery}>
                                    {record.userName}
                                </LinkTo>
                            ) : (
                                <span>{record.userName}</span>
                            )}
                        </span>
                    );
                }
            },
            {
                title: `${formatMessage({
                    id: 'stat.absenceList.departName'
                })}`,
                dataIndex: 'departName',
                key: 'departName',
                render: text => (
                    <div className={styles.ellipsis} title={text}>
                        {text}
                    </div>
                )
            },
            {
                title: `${formatMessage({
                    id: 'stat.leave.leaveName'
                })}`,
                dataIndex: 'leaveName',
                key: 'leaveName',
                width: 120,
                filters: leaveTypeList.map(item => ({ text: item.leaveName, value: item.leaveName })),
                filteredValue: this.formatQueryParam(leaveCode)
            },
            {
                title: `${formatMessage({
                    id: 'stat.out.startTime'
                })}`,
                dataIndex: 'startTime',
                key: 'startTime',
                width: 180,
                render: (text, record) => <span>{record.startTime}</span>,
                sorter: true,
                sortOrder: this.transformSortOrder('start_time', orderByField)
            },
            {
                title: `${formatMessage({
                    id: 'stat.out.endTime'
                })}`,
                dataIndex: 'endTime',
                key: 'endTime',
                width: 180,
                render: (text, record) => <span>{record.endTime}</span>,
                sorter: true,
                sortOrder: this.transformSortOrder('end_time', orderByField)
            },
            {
                title: `${formatMessage({
                    id: 'stat.out.outLong'
                })}`,
                dataIndex: 'leaveLong',
                key: 'leaveLong',
                width: 100,
                render: (text, record) => <span>{dateConversion(record.leaveLong, 8)}</span>,
                sorter: true,
                sortOrder: this.transformSortOrder('leave_long', orderByField)
            },
            {
                title: `${formatMessage({
                    id: 'stat.report.leaveState'
                })}`,
                dataIndex: 'leaveStatus',
                key: 'leaveStatus',
                width: 180,
                filters: leaveStatusList.map(item => ({ text: item.dictName, value: item.dictValue })),
                filteredValue: this.formatQueryParam(leaveStatus),
                render: (text, record) =>
                    leaveStatusList &&
                    leaveStatusList.map(item => {
                        if (record.leaveStatus && item.dictValue === record.leaveStatus.toString()) {
                            return (
                                <div>
                                    {this.renderDot(record.leaveStatus.toString())}
                                    {item.dictName}
                                </div>
                            );
                        }
                        return '';
                    })
            },
            {
                title: `${formatMessage({
                    id: 'stat.absence.action'
                })}`,
                key: 'action',
                fixed: 'right',
                width: 240,
                render: (text, record) => {
                    const { applicationNo, applicationCancelNo } = record;

                    // const isOldLeave = /LEAVE/.test(applicationNo);
                    // const isOldLeaveCancel = /CANCEL/.test(applicationCancelNo);
                    const isOldLeave = applicationNo.indexOf('-') === -1;
                    const isOldLeaveCancel = applicationCancelNo.indexOf('-') === -1;

                    const newUrl = '/personal/portal/myAuditRead/myAuditReadDetail';
                    const newQuery = { applicationNo };

                    const leaveUrl = isOldLeave
                        ? '/office/institutions/flowManage/fullApprovalProcess/processDetail'
                        : newUrl;
                    const cancelLeaveUrl = isOldLeaveCancel
                        ? '/office/personnelManagement/attendance/timetag/attendRecord/clockRecord'
                        : newUrl;

                    const leaveQuery = isOldLeave ? { applicationNo, linkFrom: '1' } : newQuery;

                    const leaveCancelQuery = isOldLeaveCancel
                        ? { applicationNo: applicationCancelNo }
                        : { applicationNo: applicationCancelNo };

                    return (
                        <span>
                            {record.applicationCancelNo ? (
                                <Fragment>
                                    <LinkTo
                                        to={cancelLeaveUrl}
                                        query={leaveCancelQuery}
                                        onClick={async (e, url) => {
                                            // 埋点
                                            await eventTrack({
                                                eventName: 'personnel_management_attendance_leaveRecord_operator_click',
                                                eventProps: {
                                                    lable: '请假记录-操作-销假详情',
                                                    tabs: '请假记录'
                                                }
                                            });
                                            history.push(url);
                                        }}
                                    >
                                        销假详情
                                    </LinkTo>
                                    <Divider type="vertical" />
                                </Fragment>
                            ) : (
                                ''
                            )}

                            <LinkTo to={leaveUrl} query={leaveQuery}>
                                {formatMessage({
                                    id: 'stat.report.toLeaveDetail'
                                })}
                            </LinkTo>
                            <Divider type="vertical" />
                            <LinkTo
                                to="/office/personnelManagement/attendance/timetag/attendRecord/clockRecord"
                                query={{
                                    id: record.employeeCode,
                                    name: record.userName,
                                    startTime: record.startTime,
                                    endTime: record.endTime
                                }}
                            >
                                {formatMessage({
                                    id: 'stat.absence.seeDetail'
                                })}
                            </LinkTo>
                        </span>
                    );
                }
            }
        ];
        return column;
    };

    render() {
        const { loading, leaveRecord, form, location } = this.props;
        const { query } = location;
        const { startTime, endTime, quarter } = query;
        const { leaveData, pagination } = leaveRecord;
        const columns = this.getColumns();
        const { locale } = new Locale('stat.overtime');

        const {
            query: { companyCode, departmentCode }
        } = location;
        const initCompanyDepart =
            companyCode || departmentCode ? { companyId: companyCode, departmentId: departmentCode } : undefined;

        const config = [
            {
                field: 'companyDepart',
                label: '机构',
                config: {
                    initialValue: initCompanyDepart
                },
                component: <CompanyDepartPlus />
            },
            {
                field: 'userName',
                label: '员工',
                component: <Input placeholder="输入姓名" />
            },
            {
                field: 'date',
                config: {
                    initialValue: {
                        range: [
                            typeof startTime === 'undefined' ? moment().startOf('month') : moment(startTime),
                            typeof endTime === 'undefined' ? moment() : moment(endTime)
                        ],
                        quarter: quarter ? Number(quarter) : 1,
                        type: ''
                    }
                },
                component: (
                    <DateRange
                        range
                        dateTypes={[
                            {
                                label: '本周',
                                type: 'week'
                            },
                            {
                                label: '本月',
                                type: 'month'
                            },
                            {
                                label: '本年',
                                type: 'year'
                            }
                        ]}
                    />
                )
            }
        ];

        return (
            <PageHeaderWrapper>
                <Form layout="inline" onSubmit={this.handleSubmit}>
                    <Card
                        bordered={false}
                        title={formatMessage({
                            id: 'stat.name.qjjl'
                        })}
                        extra={
                            <Fragment>
                                <Button type="primary" htmlType="submit">
                                    {locale('form.search', false)}
                                </Button>
                                <AuthComponent code={this.authCode('export')}>
                                    <Button
                                        style={{ marginLeft: '5px' }}
                                        onClick={this.handleExport}
                                        disabled={loading}
                                    >
                                        导出
                                    </Button>
                                </AuthComponent>
                            </Fragment>
                        }
                    >
                        <Row type="flex" className="searchTitle">
                            <Col>
                                <QuickForm form={form} config={config} />
                            </Col>
                        </Row>
                    </Card>
                </Form>
                <Card bordered={false} style={{ marginTop: '12px' }} className={styles.card}>
                    <Table
                        columns={columns}
                        loading={loading}
                        dataSource={leaveData}
                        onChange={this.changeTable}
                        rowKey="id"
                        pagination={false}
                        scroll={{ x: 'max-content' }}
                    />
                    <Pagination
                        onChange={this.changePagination}
                        total={pagination.total}
                        current={query.pageNo}
                        pageSize={query.pageSize}
                        loading={loading}
                    />
                </Card>
            </PageHeaderWrapper>
        );
    }
}

export default withRoutePage(
    connect(({ leaveRecord, loading }) => ({ leaveRecord, loading: loading.models.leaveRecord }))(
        Form.create()(LeaveRecord)
    )
);
